<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" size="small" @click="addDialogVisible = true">新增</el-button>
        </el-col>
      </el-row>
      <el-table :data="cooperList" border stripe v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading">
        <el-table-column label="封面图">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              :title="scope.row.name"
              trigger="hover">
              <img :src="scope.row.url.url" style="max-height: 200px;max-width: 200px" />
              <img slot="reference" :src="scope.row.url.url" style="max-height: 50px;max-width: 50px" />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="名称"></el-table-column>
        <el-table-column prop="navigation.title" label="栏目"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="delPhoto(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[10, 20, 30, 40,50]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog :title="dialog_title" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!--内容主题区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
        <el-form-item label="类别" prop="column_id">
          <el-select v-model="addForm.column_id" placeholder="请选择文章类别" style="width: 100%">
            <el-option v-for="(item,index) in typeList" :key="index" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img" ref="imageRef">
          <el-upload
            ref="imgref"
            :action="upload.url"
            :headers="upload.headers"
            :accept="upload.accept"
            list-type="picture-card"
            :file-list="addForm.img"
            :data="upload.data"
            :limit="upload.limitCount"
            :on-remove="handleRemove"
            :on-exceed="onExceed"
            :on-success="onSuccess"
            :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addForm.status"></el-switch>
        </el-form-item>
      </el-form>
      <!--底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCooperation">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "index",
  data(){
    let checkImg = (rule, value, callback) => {
      if (!this.hasFmt) { //hasFmt设置为true/false
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    }
    return{
      addDialogVisible:false,
      hasFmt:false,
      queryInfo:{
        title:'',
        limit: this.$global_limit,
        page: this.$global_page
      },
      loading:false,
      total:0,
      cooperList:[],
      //图片url
      dialogImageUrl: '',
      //图片弹出框
      dialogVisible: false,
      dialog_title:'新增',
      //图片配置
      upload: {
        url: this.$action_url,
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data:{
          folder:'cooperation_img'
        },
        name: 'file',
        accept: 'image/*',
        limitCount: 1,
      },
      addForm:{
        id:0,
        column_id:'',
        title:'',
        img:[],
        status:true
      },
      typeList:[],
      addFormRules:{
        title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 116, message: '长度在 2 到 116 个字符', trigger: 'blur' }
        ],
        column_id:[
          { required: true, message: '请选择所属类别', trigger: 'change' }
        ],
        img: [{ required: true, validator: checkImg }]
      }
    }
  },
  created() {
    this.getPhotoList()
    this.getTypeList()
  },
  methods:{
    async getTypeList(){
      const {data: res} = await this.$http.get('dashboard/nav_list')
      if (res.code !== 200) return this.$message.error('获取菜单列表失败')
      this.typeList = res.data.list;
    },
    //列表
    async getPhotoList(){
      const {data: res} = await this.$http.get('dashboard/photo_list', {params: this.queryInfo})
      if (res.code !== 200) return this.$message.error(res.data.message)
      this.cooperList = res.data.list
      this.total = res.data.totalCount
      this.loading = false
    },
    addDialogClose(){
      this.$refs.imgref.clearFiles()
      this.$refs.addFormRef.resetFields()
    },
    //新增
    addCooperation(){
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        const {data: result} = await this.$http.post('dashboard/save_photo', this.addForm)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('新增成功')
        this.addDialogVisible = false
        this.addForm.id = 0;
        this.dialog_title = '新增'

        this.getPhotoList();
      })
    },
    handleSizeChange (newSize) {
      this.queryInfo.limit = newSize
      this.getPhotoList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.page = newPage
      this.getPhotoList()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onSuccess(response, file, fileList){
      if (response.code !== 200) return this.$message.error(response.data.message)
      this.hasFmt = true;
      const path = {url:this.$http_url + 'storage/' + response.data.list.path,uid:file.uid,name:file.name}
      this.addForm.img.push(path)
      this.$refs.imageRef.clearValidate();
    },
    handleRemove(file){
      const i = this.addForm.img.findIndex(x => x.image === file)
      //通过数组的splice方法 把图片从img_path 数组中删除
      this.addForm.img.splice(i, 1)
      if(this.addForm.img.length === 0){
        this.hasFmt = false;
      }
      this.$refs.imageRef.validate();
    },
    onExceed(files, fileList){
      if(files.length === 1){
        return this.$message.error('图片超出1张图片的限制,请删除后重新上传')
      }
    },
    async showEditDialog(id){
      this.dialog_title = '编辑'
      this.addDialogVisible = true
      this.hasFmt = true;
      this.pathList = []
      const {data: res} = await this.$http.get('dashboard/show_photo/' + id)
      if (res.code !== 200) return this.$message.error('获取失败');
      this.addForm = res.data.list;
    },
    async delPhoto(id){
      const configResult = await this.$confirm('此操作将永久删除该合作客户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (configResult !== 'confirm') return this.$message.info('已取消删除')
      const {data: result} = await this.$http.delete('dashboard/del_photo/' + id)
      if (result.code !== 200) return this.$message.error(result.data.message)
      this.$message.success('删除成功')

      //删除成功后页码改变返还为上一页
      let totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit);
      let currentPage = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page;
      this.queryInfo.page = this.queryInfo.page < 1 ? 1 : currentPage;

      this.getPhotoList();
    }
  }
}
</script>

<style scoped>

</style>
